<template>
	<view>
		<view class="header w100 flexw">

			<view class="flex u-rela w100 u-p-t-20 u-p-b-20 u-p-l-28 u-p-r-28">
				<image class="image" src="@/pagesIndex/static/search.png"></image>
				<input class="input" :focus="true" @confirm="doneInput" type="text" confirm-type="search"
					:adjust-position="false" @input="onInput" placeholder="搜索城市" v-model="searchValue" />
			</view>
		</view>

		<scroll-view @scroll="scrollTo" class="w100" scroll-y="true" :scroll-into-view="scrollIntoId"
			:style="{height:scrollHeight}" @touchmove.stop.prevent @scrolltolower="scrolltolower">

			<!-- 城市列表 -->
			<view v-if="searchValue == ''" v-for="(item, index) in list" :id="item.idx" :key="item.idx">
				<view :class="['letter-header',scrollIntoId===item.idx?'active':'']">{{ item.idx }}</view>
				<view class="bg-white">
					<view class="city-div" v-for="(city, i) in item['cities']" :key="i" @tap="back_city(city)">
						<text class="city">{{ city.city_name }}</text>
					</view>
				</view>

			</view>
			<!-- 搜索结果 -->
			<view class="bg-white">
				<view class="city-div" v-for="(item, index) in searchList" :key="index" @tap="back_city(item)">
					<text class="city">{{ item.city_name }}</text>
				</view>
			</view>


			<view class="placeholder footer"></view>
		</scroll-view>

		<!-- 右侧字母 -->
		<view class="letters" id="list" v-if="searchValue == ''" @touchstart.stop.prevent="touchStart"
			@touchmove.stop.prevent="touchMove" @touchend="touchEnd">
			<view :class="['fmin',scrollIntoIdStyle===item.idx?'active':'']" v-for="item in letter" :key="item.idx">
				{{ item.idx }}
			</view>
		</view>

		<!-- 选中之后字母 -->
		<view class="mask" v-if="touchmove">
			<view class="mask-r bold">{{scrollIntoId}}</view>
		</view>
	</view>
</template>

<script>
	import {
		getCitys
	} from '@/api/common';
	let currentLetter = 'A';
	let current = 0;
	export default {

		data() {
			return {
				statusBar: '0px',
				customBar: '45px',

				winHeight: 0,
				itemHeight: 0,
				winOffsetY: 0,
				touchmove: false,


				scrollHeight: this.statusBarHeight,
				ImgUrl: this.ImgUrl,
				letter: [],

				searchValue: '',
				scrollIntoId: 'A',
				scrollIntoIdStyle: 'A',
				list: [],
				tId: null,
				searchList: [],
				showMask: false,
				disdingwei: true,
				cacheLocation: '', //最近访问
				position: '', //定位获取的位置

				po_tips: '重新定位',
				hotCity: '',
				topList: [],
				isClick: false,
			}
		},
		watch: {
			list() {
				setTimeout(() => {
					this.setList()
				}, 100)
			}
		},

		onLoad() {
			this.scrollHeight = uni.getSystemInfoSync().windowHeight - parseInt(this.customBar) + 'px'
			//获取存储的最近访问
			var that = this
			uni.getStorage({
				key: 'location_key',
				success: function(res) {
					that.cacheLocation = res.data
				}
			});
			//获取定位 经度纬度
			that.getWarpweft()
			this.getCitys()



		},
		methods: {
			async getCitys() {
				const Citys = await getCitys();
				this.letter = Citys.data.classify_nav;
				this.list = Citys.data.city_nav;
				this.hotCity = Citys.data.hot_city;
				this.$nextTick(() => {
					this.getNodesInfo();
				})
			},
			back() {
				//你自己实现 返回上一页
				uni.navigateBack()
			},
			scrollTo(e) {
				if (this.isClick) {
					this.isClick = false;
					return;
				}
				const offsetTop = e.target.scrollTop;
				for (let i = 0; i < this.topList.length; i++) {
					const h1 = this.topList[i];
					const h2 = this.topList[i + 1];
					if (offsetTop <= h2 && offsetTop > h1) {
						this.scrollIntoIdStyle = this.letter[i].idx;
					}
				}
			},
			scrolltolower() {
				console.log(123);
				setTimeout(() => {
					this.scrollIntoIdStyle = this.letter[this.topList.length - 1].idx;
				}, 80);
			},
			getNodesInfo() {
				const query = uni.createSelectorQuery().in(this);
				query.selectAll(".letter-header").boundingClientRect().exec(res => {
					let nodes = res[0];
					let arr = [];
					nodes.map(item => {
						arr.push(item.top - 56);
					})
					this.topList = arr;
					console.log('arr', arr);
				})
			},
			getLetter(list, index) {
				for (var i = 0; i < list.length; i++) {
					const item = list[i]
					current++
					if (index === current) {
						currentLetter = item.idx
						break
					}
					for (var j = 0; j < item.cities.length; j++) {
						current++
						if (index === current) {
							currentLetter = item.idx
							return
						}
					}
				}
			},
			setList() {
				uni.createSelectorQuery()
					.in(this)
					.select('#list')
					.boundingClientRect()
					.exec(ret => {
						this.winOffsetY = ret[0].top
						this.winHeight = ret[0].height
						this.itemHeight = this.winHeight / this.list.length
					})

			},
			touchStart(e) {
				this.touchmove = true
				let pageY = e.touches[0].pageY
				let index = Math.floor((pageY - this.winOffsetY) / this.itemHeight)
				if (this.list[index]) {
					this.scrollIntoId = this.list[index].idx;
					this.scrollIntoIdStyle = this.list[index].idx;
					this.isClick = true;
				}
			},
			touchMove(e) {
				let pageY = e.touches[0].pageY
				let index = Math.floor((pageY - this.winOffsetY) / this.itemHeight)
				if (this.list[index] && this.list[index].idx === this.scrollIntoId) {
					return false
				}
				if (this.list[index]) {
					this.scrollIntoId = this.list[index].idx;
					this.scrollIntoIdStyle = this.list[index].idx;
				}
			},
			touchEnd() {
				this.touchmove = false
				this.touchmoveIndex = -1
			},

			doneInput() {
				uni.hideKeyboard()
			},
			move(e) {
				console.log(e);
			},
			getId(index) {
				return this.letter[index];
			},
			query(source, text) {
				let res = [];
				var self = this;
				let len = source.length
				var text = text.toLowerCase()
				for (let i = 0; i < len; i++) {
					//单字母搜索
					if (text.length == 1 && /^[a-zA-Z]$/.test(text)) {
						let arr = []
						let idx = text.toUpperCase()
						if (idx == source[i].idx) {
							console.log(source[i]);
							return source[i].cities
						}
					}
					//其它搜索
					if (source[i].cities) {
						let _len = source[i].cities.length
						for (var n = 0; n < _len; n++) {
							let _item = source[i].cities[n]
							if (new RegExp('^' + text).test(_item.city_name)) {
								res.push(_item);
								continue;
							}
							if (new RegExp('^' + text).test(_item.city_pinyin)) {
								res.push(_item);
								continue;
							}
							if (new RegExp('^' + text).test(_item.py)) {
								res.push(_item);
								continue;
							}

						}
					}
				}

				return res;
			},

			isString(obj) {
				return typeof obj === 'string';
			},

			onInput(e) {
				const value = e.target.value;
				if (value !== '' && this.list) {
					const queryData = this.query(this.list, String(value).trim());
					this.searchList = queryData;
					this.disdingwei = false
				} else {
					this.searchList = [];
					this.disdingwei = true
				}
			},

			back_city(item, hasLocation = false) {
				console.log(item);
				if (item) {
					//是否是定位 
					if (hasLocation) {
						item = {
							city_name: item.city,
							location: item
						}
					}
					uni.$emit('selectCity', item);
					//unshift 把数据插入到首位，与push相反
					if (!this.cacheLocation) this.cacheLocation = []
					this.cacheLocation.unshift(item)
					this.searchValue = "";
					this.disdingwei = true
					var arr = this.cacheLocation
					//数组去重
					function distinct(arr) {
						let newArr = []
						for (let i = 0; i < arr.length; i++) {
							if (newArr.indexOf(arr[i]) < 0) {
								newArr.push(arr[i])
							}
						}
						return newArr
					}
					this.cacheLocation = distinct(arr).slice(0, 5)
					// uni.setStorage({
					// 	key: 'location_key',
					// 	data: this.cacheLocation
					// });
				}
				uni.setStorageSync('city', item)
				this.back()
			},
			getWarpweft() {
				//自己写吧
				var that = this
				that.po_tips = '定位中...'
				setTimeout(() => {
					that.po_tips = '定位失败'
				})
			}
		}
	};
</script>

<style scoped lang="scss">
	.fsmall {
		font-size: 26rpx;
	}

	.fmiddle {
		font-size: 28rpx;
	}

	.blue {
		color: #007AFF;
	}

	.bold {
		font-weight: 600;
	}

	.flex {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.mask {
		position: fixed;
		z-index: 3;
		top: 40%;
		left: 40%;
	}

	.mask-r {
		height: 120rpx;
		width: 120rpx;
		border-radius: 60rpx;
		display: flex;
		background: rgba(0, 0, 0, 0.5);
		backdrop-filter: blur(5px);
		justify-content: center;
		align-items: center;
		font-size: 40rpx;
		color: #FFFFFF
	}

	.content {
		height: 100%;
		width: 100%;
		background-color: #ffffff;
	}

	.header {
		width: 100%;
		position: relative;
		z-index: 8;
	}


	.back_div {
		width: 100rpx;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.back_img {
		width: 35rpx;
		height: 35rpx;
	}

	.image {
		width: 16px;
		height: 16px;
		position: absolute;
		left: 30px;
	}

	.input {
		width: 100%;
		font-size: 26rpx;
		height: 72rpx;
		border-radius: 44rpx;
		background-color: #fff;
		padding-left: 76rpx;
		padding-right: 32rpx;
		box-sizing: border-box;
	}

	.title {
		font-size: 30rpx;
		color: white;
	}

	.show {
		left: 0;
		width: 100%;
		transition: left 0.3s ease;
	}

	.hide {
		left: 100%;
		width: 100%;
		transition: left 0.3s ease;
	}


	.title {
		font-size: 30rpx;
		color: white;
	}

	.letters {
		position: absolute;
		right: 0;

		width: 80rpx;
		color: #333333;
		top: 150px;
		text-align: center;
		font-size: 20rpx;
		font-weight: 500;
	}

	.letters .fmin {
		height: 18px;

		&.active {
			color: #FFCF0B;
		}
	}


	.letter-header {
		height: 26px;
		font-size: 28rpx;
		color: #333;
		padding-left: 28rpx;
		box-sizing: border-box;
		display: flex;
		align-items: center;

		&.active {
			color: #FFCF0B;
		}
	}

	.city-div {
		display: flex;
		align-items: center;
		height: 36px;
		margin: 0 28rpx;
		border-bottom: 1rpx solid #ECECEC;

		.city {
			font-size: 14px;
			color: #333;
		}

	}



	.dingwei {
		width: 90%;
		margin: auto;
		padding-top: 25rpx;
		box-sizing: border-box;
		margin-bottom: 26rpx;
	}

	.dingwei .grey {
		margin-bottom: 25rpx;
	}

	.dingwei_city {
		width: 100%;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
	}

	.dingwei_city_one {
		height: 60rpx;
		background-color: #F5F5F5;
		border-radius: 30rpx;
		font-size: 26rpx;
		padding: 0 20rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 0 20rpx 20rpx 0;
	}


	.dingweis {
		width: 32rpx;
		height: 32rpx;
	}

	.dingwei_city_zuijin {
		display: flex;
		justify-content: flex-start;
		flex-wrap: wrap;
	}
</style>
